<template>
  <div class="import_quota_dialog">
    <el-drawer v-model="_isOpen" size="1140" modal-class="dialog_drawer">
      <template #header>
        <div class="drawer_title">选择定额模板</div>
      </template>
      <div class="drawer_content">
        <div class="content_tree">
          <template v-if="treeData.length > 0">
            <p class="pl10 pt24 pb20"><img src="@/assets/images/file-icon.png" alt="" class="mr16" />定额工程类型</p>
            <el-tree
              :data="treeData"
              :props="{
                children: 'childFolder',
                label: 'folderName',
                class: 'tree_node'
              }"
              @node-click="handleNodeClick"
            >
              <template #default="{ node }">
                <img src="@/assets/images/file-icon.png" />
                <span class="ml7" :title="node.label || '-'">{{ node.label }}</span>
              </template>
            </el-tree>
          </template>

          <div v-else style="display: flex; justify-content: center; width: 100%">
            <el-empty description="暂无数据" />
          </div>
        </div>
        <div class="content_list">
          <div class="list_input">
            <el-input
              v-model="searchkey"
              clearable
              style="width: 160px"
              placeholder="请输入工程名称"
              :prefix-icon="Search"
              :disabled="JSON.stringify(currTreeNode) === '{}'"
              @change="getProjectFun"
            />
          </div>
          <div class="temp_list mt20">
            <p class="title">{{ currTreeNode.folderName }}</p>
            <div
              class="temp_item"
              :class="{ active: currQuota.projectId === item.projectId }"
              v-for="(item, index) of quotaList"
              :key="index"
              @click="changeQuota(item)"
            >
              <p class="text-over" :title="item.projectName || '-'">{{ item.projectName || "-" }}</p>
            </div>
          </div>
        </div>
        <div class="content_table">
          <el-table ref="tableRef" :data="tableData" stripe style="width: 100%" @selection-change="handleSelectionChange">
            <template #empty>
              <el-empty description="这里暂时什么都没有" />
            </template>
            <el-table-column type="selection" width="55" />
            <el-table-column label="序号" fixed type="index" width="60" />
            <el-table-column prop="quotaName" show-overflow-tooltip label="定额名称" width="200">
              <template #default="scope">
                {{ scope.row.quotaName || "-" }}
              </template>
            </el-table-column>
            <el-table-column prop="standardDesc" show-overflow-tooltip label="材料及工艺说明" width="200">
              <template #default="scope">
                <el-button type="primary" class="underline" link @click="openMaterialDialog(scope.row)">
                  <p class="text-over" style="max-width: 180px">{{ scope.row.standardDesc || "-" }}</p>
                </el-button>
              </template>
            </el-table-column>
            <el-table-column prop="unit" show-overflow-tooltip label="单位" width="135">
              <template #default="scope">
                {{ useCodeArrStore().getDictName("shop_unit", scope.row.unit) }}
                <!-- <p>{{ scope.row.unit }}</p> -->
              </template>
            </el-table-column>
            <el-table-column prop="lostRate" show-overflow-tooltip label="耗损率" width="135">
              <template #default="scope"> {{ scope.row.lostRate || "-" }}%</template>
            </el-table-column>
            <el-table-column label="报价">
              <el-table-column prop="mainQuoteMoney" label="定额主材" width="120">
                <template #default="scope">
                  <!-- <p>{{ scope.row.mainQuoteMoney || "-" }}</p> -->
                  <el-button class="underline" type="primary" link @click="openCailiaoDialog(scope.row, 1)">
                    ¥{{ scope.row.mainQuoteMoney || "-" }}
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column prop="auxiliaryQuoteMoney" label="定额辅材" width="120">
                <template #default="scope">
                  <!-- <p>{{ scope.row.auxiliaryQuoteMoney || "-" }}</p> -->
                  <el-button class="underline" type="primary" link @click="openCailiaoDialog(scope.row, 2)">
                    ¥{{ scope.row.auxiliaryQuoteMoney || "-" }}
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column prop="workerQuoteMoney" label="人工" width="120">
                <template #default="scope">
                  <el-button class="underline" type="primary" link @click="openArtificialDialog(scope.row)">
                    ¥{{ scope.row.workerQuoteMoney || "-" }}
                  </el-button>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column prop="quoteTotalMoney" label="报价合计" width="120">
              <template #default="scope"> ¥{{ scope.row.quoteTotalMoney || "-" }} </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <template #footer>
        <div class="drawer_footer">
          <el-button class="cancel_btn" @click="cancelClick">取消</el-button>
          <el-button class="confirm_btn" @click="confirmClick" :disabled="selectedList.length <= 0">
            已选中({{ selectedList.length }})
          </el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 材料工艺详情抽屉 -->
    <materialDrawer v-model:isOpen="materialIsOpen" :optionInfo="optionInfoMaterial" />

    <!-- 固定商品-主材辅材明细列表弹窗 -->
    <cailiaoDetailList v-model:isOpen="cailiaoIsOpen" :optionInfo="optionInfoCailiao" />

    <!-- 组合条件-主材辅材明细列表弹窗 -->
    <cailiaoDetailListZuHe v-model:isOpen="cailiaoIsOpenZuHe" :optionInfo="optionInfoCailiaoZuHe" />

    <!-- 人工明细列表弹窗 -->
    <artificialDetailList v-model:isOpen="artificialIsOpen" :optionInfo="optionInfoArtificial" />
  </div>
</template>

<script setup>
import {
  getfolderTree,
  getProject,
  getQuotaList2,
  inventoryAddQuota,
  packageAddQuota,
  quotaProductList,
  quotaWorkerList
} from "@/apis/quote-price/following";
import { computed, ref } from "vue";
import { Search } from "@element-plus/icons-vue";
import { quotaProductConditionList } from "@/apis/combo-price";
import { ElMessage } from "element-plus";
import useCodeArrStore from "@/store/modules/select";
import cailiaoDetailList from "./cailiaoDetailList.vue"; //主材、辅材明细---固定商品
import cailiaoDetailListZuHe from "./cailiaoDetailListZuHe.vue"; //主材、辅材明细---条件组合
import artificialDetailList from "./artificialDetailList.vue"; //人工明细
import materialDrawer from "./materialDetail.vue";

const props = defineProps({
  isOpen: { type: Boolean, default: false },
  optionInfo: { type: Object, default: () => ({}) },
  doSubmit: { type: Boolean, default: true }
});

const emits = defineEmits(["update:isOpen", "submitOk"]);

const _isOpen = computed({
  get: () => props.isOpen,
  set: newVal => emits("update:isOpen", newVal)
});

const tableRef = ref();
const treeData = ref([]); //定额工程类型tree
const currTreeNode = ref({}); //选中的工程类型树节点
const searchkey = ref("");
const quotaList = ref([]); //定额列表
const currQuota = ref({});
const tableData = ref([]);
const selectedList = ref([]);
const materialIsOpen = ref(false);
const optionInfoMaterial = ref({ type: "view", detail: {} });
const cailiaoIsOpen = ref(false); //固定商品-主材辅材明细列表弹窗
const optionInfoCailiao = ref({ type: "zhu", detail: {} });
const cailiaoIsOpenZuHe = ref(false); //组合条件-主材辅材明细列表弹窗
const optionInfoCailiaoZuHe = ref({ type: "zhu", detail: {} });
const artificialIsOpen = ref(false); //人工明细列表弹窗
const optionInfoArtificial = ref({ detail: {} });

/**查询定额工程文件夹tree */
const getfolderTreeFun = async () => {
  const { data } = await getfolderTree();
  treeData.value = data;
};

/**切换tree node定额工程类型 */
const handleNodeClick = node => {
  if (node.childFolder.length > 0) return;
  currTreeNode.value = node;
  getProjectFun();
};

/**查询工程类型 */
const getProjectFun = () => {
  getProject({ folderId: currTreeNode.value.folderId, projectName: searchkey.value }).then(res => {
    if (res.code === 200) {
      quotaList.value = res.data || [];
    }
  });
};

const changeQuota = item => {
  currQuota.value = item;
  getQuotaList2({ projectId: item.projectId, budgetId: props.optionInfo.budgetId }).then(res => {
    if (res.code === 200) {
      tableData.value = res.data;
    }
  });
};

const openCailiaoDialog = (item, type = 1) => {
  console.log(99999, item);
  if (type === 2 && (item.mainProductShowType === 2 || item.auxiliaryProductShowType === 2)) {
    //条件组合
    cailiaoIsOpenZuHe.value = true;
  } else {
    //固定商品
    cailiaoIsOpen.value = true;
  }
  getProductsByContentIdFun(item, type);
};

//查询主材、辅材明细列表 type 1-主材 2-辅材材
const getProductsByContentIdFun = async (item, type = 1) => {
  if (type === 2 && (item.mainProductShowType === 2 || item.auxiliaryProductShowType === 2)) {
    //主材mainProductShowType 辅材auxiliaryProductShowType :1-具体商品 2-条件组合

    console.log("条件组合");

    quotaProductConditionList(item.quotaId, type).then(res => {
      if (res.code === 200) {
        optionInfoCailiaoZuHe.value.actionType = "view";
        optionInfoCailiaoZuHe.value.type = type === 1 ? "zhu" : "fu";
        optionInfoCailiaoZuHe.value.project = { ...item };
        optionInfoCailiaoZuHe.value.detail = { ...res.data, contentId: item.contentId, _time: new Date().getTime() };
        optionInfoCailiaoZuHe.value.getDetailList = getProductsByContentIdFun;
      }
    });
  } else {
    //非条件组合
    console.log("固定商品", item);

    quotaProductList({ quotaId: item.quotaId, productType: type }).then(res => {
      if (res.code === 200) {
        optionInfoCailiao.value.dialogType = "de"; //ys-预算报价  de-定额模板
        optionInfoCailiao.value.actionType = "view";
        optionInfoCailiao.value.type = type === 1 ? "zhu" : "fu";
        optionInfoCailiao.value.project = { ...item, showSign: 0 };
        optionInfoCailiao.value.detail = { ...res.data, contentId: item.contentId, _time: new Date().getTime() };
        optionInfoCailiao.value.getDetailList = getProductsByContentIdFun;
      }
    });
  }
};

const openArtificialDialog = item => {
  artificialIsOpen.value = true;
  getWorkerListByContentIdFun(item);
};

const getWorkerListByContentIdFun = item => {
  quotaWorkerList({ quotaId: item.quotaId }).then(res => {
    if (res.code === 200) {
      console.log("人工明细", res.data);
      optionInfoArtificial.value.dialogType = "de"; //ys-预算报价  de-定额模板
      optionInfoArtificial.value.actionType = "view";
      optionInfoArtificial.value.detail = { ...res.data, _time: new Date().getTime() };
    }
  });
};

const openMaterialDialog = item => {
  materialIsOpen.value = true;
  optionInfoMaterial.value.type = "view";
  optionInfoMaterial.value.detail = { ...item, _time: new Date().getTime() };
};

const handleSelectionChange = list => {
  selectedList.value = list;
};

const reset = () => {
  selectedList.value = [];
  tableRef.value.clearSelection();
  searchkey.value = "";
  currTreeNode.value?.folderId && getProjectFun();
};

const cancelClick = () => {
  reset();
  _isOpen.value = false;
};

const confirmClick = () => {
  if (props.doSubmit) {
    if (props.optionInfo.type === 1) {
      //常规
      inventoryAddQuota({
        spaceId: props.optionInfo.spaceId,
        budgetId: props.optionInfo.budgetId,
        quotaIds: selectedList.value.map(item => item.quotaId)
      }).then(res => {
        if (res.code === 200) {
          ElMessage({
            message: "定额导入成功",
            type: "success"
          });
          reset();
          emits("submitOk");
          _isOpen.value = false;
        }
      });
    } else if (props.optionInfo.type === 2) {
      //套餐
      packageAddQuota({
        spaceId: props.optionInfo.spaceId,
        budgetId: props.optionInfo.budgetId,
        quotaIds: selectedList.value.map(item => item.quotaId)
      }).then(res => {
        if (res.code === 200) {
          ElMessage({
            message: "定额导入成功",
            type: "success"
          });
          reset();
          emits("submitOk");
          _isOpen.value = false;
        }
      });
    }
  } else {
    emits(
      "customSubmit",
      selectedList.value.map(item => item.quotaId)
    );
  }

  // emit("changeAttr");
};

(() => {
  getfolderTreeFun();
})();
</script>
<style lang="scss">
.import_quota_dialog {
  .dialog_drawer {
    .el-drawer {
      border-radius: 20px 0px 0px 20px;
      .el-drawer__body {
        padding: 0;
      }
    }
    .drawer_title {
      font-size: 18px;
      line-height: 24px;
      color: #131414;
    }
    .drawer_content {
      display: flex;
      height: 100%;
      overflow: auto;
      border-top: 1px solid #dcdfe6;
      .content_tree {
        box-sizing: border-box;
        height: 100%;
        overflow: auto;
        width: 220px;
        border-right: 1px solid #dcdfe6;
        .tree_node {
          .el-tree-node__content {
            padding: 7px 0;
          }
        }
      }
      .content_list {
        box-sizing: border-box;
        width: 200px;
        border-right: 1px solid #dcdfe6;
        .list_input {
          padding: 20px 20px 0;
        }
        .temp_list {
          .title {
            color: #3d3d3d;
            font-weight: 700;
            line-height: 32px;
            margin-bottom: 10px;
            padding: 0 20px;
          }
          .temp_item {
            padding: 0 20px;
            margin-bottom: 10px;
            line-height: 32px;
            height: 32px;
            cursor: pointer;
            color: #86909c;
            &.active {
              background-color: #eef1f4;
              color: #3d3d3d;
            }
          }
        }
      }
      .content_table {
        box-sizing: border-box;
        width: calc(100% - 420px);
        padding: 20px;
        overflow: auto;
        height: 100%;
      }
    }
    .cancel_btn,
    .confirm_btn {
      width: 120px;
      height: 36px;
      background: #f2f3f5;
      border-radius: 2px 2px 2px 2px;
      color: #1d2129;
      border: none;
    }
    .confirm_btn {
      background: #424e66;
      color: white;
    }
    .el-drawer__footer {
      box-shadow: 0px -3px 10px 0px rgba(4, 24, 48, 0.1);
      border-radius: 0px 0px 0px 10px;
      z-index: 1;
    }
  }
}
</style>
